﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RN.ERP.Web.BasicService;
using RN.ERP.Web.EnterpriseService;
using RN.ERP.Web.ModelService;
using RN.ERP.Web.PersonService;
using Newtonsoft.Json;
using System.Web.Services;
using Fly.Common.Linq;
using System.Configuration;

namespace RN.ERP.Web
{
    public partial class RegisterLC : System.Web.UI.Page
    {
        private string AppID
        {
            get
            {//
                return HttpContext.Current.Application[ApplicationConstant.APPLICATION_ID].ToString();
            }
        }

        private string SysArea
        {
            get
            {
                return ConfigurationManager.AppSettings["sysArea"];
            }
        }

        private bool IsAppRightOpen
        {
            get
            {
                return ConfigurationManager.AppSettings["IsAppRightOpen"] == "true";
            }
        }

        private BasicServiceClient basicService = new BasicServiceClient();
        private EnterpriseServiceClient enterpriseService = new EnterpriseServiceClient();
        public override void VerifyRenderingInServerForm(Control control)
        {            // Confirms that an HtmlForm control is rendered for       
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetParams();
                BindDDLCorpType();
                BindCorpUserType();
            }
        }

        public int checkUserName()
        {
            return 0;
        }

        private void BindDDLCorpType()
        {
            //企业类型
            string result_Type = basicService.GetDictionary("CorpType", "", "02");
            if (string.IsNullOrEmpty(result_Type))
            {
                return;
            }
            Dictionary<string, string> dicCorpType = JsonConvert.DeserializeObject<Dictionary<string, string>>(result_Type);
            this.DDlCorpType.DataSource = dicCorpType;
            this.DDlCorpType.DataValueField = "Key";
            this.DDlCorpType.DataTextField = "Value";
            this.DDlCorpType.DataBind();
            this.DDlCorpType.Items.Insert(0, new ListItem("-请选择-", ""));
        }

        /// <summary>
        /// 绑定企业类型
        /// </summary>
        private void BindCorpUserType()
        {
            ////获取所有企业类型
            Dictionary<string, string> dicCorpUserType = GetCorpUserType();
            DDLCorpUserType.DataSource = dicCorpUserType;
            this.DDLCorpUserType.DataValueField = "Key";
            this.DDLCorpUserType.DataTextField = "Value";
            DDLCorpUserType.DataBind();
            DDLCorpUserType.Items.Insert(0, new ListItem("--请选择--", ""));
        }

        private Dictionary<string, string> GetDdlByDic(string type, string condition)
        {
            string result = Application[ApplicationConstant.APPLICATION_CORPUSERTYPE] == null ? string.Empty : Application[ApplicationConstant.APPLICATION_CORPUSERTYPE].ToString();
            if (string.IsNullOrEmpty(result))
            {
                return new Dictionary<string, string>();
            }
            return JsonConvert.DeserializeObject<Dictionary<string, string>>(result);
        }

        private Dictionary<string, string> GetCorpUserType()
        {
            Dictionary<string, string> ret = new Dictionary<string, string>();
            string appId = Application[ApplicationConstant.APPLICATION_ID] == null ? string.Empty : Application[ApplicationConstant.APPLICATION_ID].ToString();
            if (appId == "101")
            {
                ret.Add("2501", "施工企业");
                ret.Add("2506", "装饰企业");
                ret.Add("2301", "门窗企业");
                ret.Add("30", "商砼企业");
            }
            else
            {
                ret = GetDdlByDic("CorpUserType", "");
            }
            return ret;
        }

        /// <summary>
        /// 获取传递参数
        /// </summary>
        private void GetParams()
        {
            string userName = Request.Params["userName"] ?? string.Empty;
            string passWord = Request.Params["passWord"] ?? string.Empty;
            string dogId = Request.Params["dogId"] ?? string.Empty;
            string type = Request.Params["type"] ?? string.Empty;

            ////异步调用方法
            if (Request.Params["action"] != null)
            {
                string action = Request.Params["action"];
                switch (action)
                {
                    case "CorpRegEdit":
                        CorpRegEdit(userName,passWord,dogId,type);
                        break;
                }
            }
        }

        private void CorpRegEdit(string userName, string passWord, string dogId, string type)
        {
            string msg = string.Empty;
            if (!string.IsNullOrEmpty(passWord))
            {
                BasicServiceClient client = new BasicServiceClient();
                EnterpriseService.EnterpriseServiceClient enterpriseServiceClient = new EnterpriseService.EnterpriseServiceClient();
                UserInfo userInfo = JsonConvert.DeserializeObject<UserInfo>(client.DoLoginWithAuthority(userName, passWord, dogId, type, string.Empty, AppID));
                Tb_Corp_CompanyInfo corp = new Tb_Corp_CompanyInfo();
                T_Sys_Users user = new T_Sys_Users();
                Guid guid = Guid.Empty;
                Guid.TryParse(userInfo.UserGuid, out guid);
                if (userInfo.Result)
                {  
                    string sysArea = ConfigurationManager.AppSettings["sysArea"];
                    if (userInfo.RoleType == "User" && IsAppRightOpen && !IsAppRightValid(userInfo.UserGuid))
                    {
                        var result1 = "{\"result\":1,\"message\":\"没有权限！\"}";
                        OutputData(result1);
                        return;
                    }
                    else
                    {
                        int appid = 0;
                        int.TryParse(System.Configuration.ConfigurationManager.AppSettings["AppID"], out appid);
                        string areaCode = System.Configuration.ConfigurationManager.AppSettings["sysArea"];
                        List<QueryCompanyInfoCondition> listCondition = new List<QueryCompanyInfoCondition>();
                        QueryCompanyInfoCondition companyInfoQuery = new QueryCompanyInfoCondition();
                        companyInfoQuery.CorpUserGuid = new Fly.Common.Linq.ParameterValue<Guid>() { O = OptEnum.Equal, V = guid };
                        listCondition.Add(companyInfoQuery);
                        string companyInfo = enterpriseServiceClient.GetCompanyInfo(JsonConvert.SerializeObject(listCondition), sysArea);
                        var result = "{\"result\":0,\"userInfo\":" + JsonConvert.SerializeObject(userInfo) + ",\"corpInfo\":" + companyInfo + "}";
                        OutputData(result);

                    }
                }
                else
                {
                    var result = "{\"result\":1,\"message\":"+userInfo.Message+"}";
                    OutputData(result);

                }
            }
            else
            {
                msg  = "{\"result\":1,\"message\":\"身份确认失败！\"}";
            }
            OutputData(msg);
        }

        private bool IsAppRightValid(string UserGuid)
        {
            BasicServiceClient client = new BasicServiceClient();
            return client.IsAppRightValid(int.Parse(AppID), Guid.Parse(UserGuid), SysArea);
        }

        /// <summary>
        /// 输出JSON格式数据到页面
        /// </summary>
        /// <param name="dataStr"></param>
        private void OutputData(string dataStr)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Write(dataStr);
            HttpContext.Current.Response.End();
        }

        #region Ajax
        [WebMethod]
        public static string VerifyCorpReg(string userName, string orgCode, string corpType, string dogId)
        {
            EnterpriseServiceClient enterpriseService = new EnterpriseServiceClient();
            int retUser = 0;
            int retOrg = 0;
            //验证用户名
            bool verifyUser = enterpriseService.IsUserExisted(userName, string.Empty);
            if (verifyUser == true)
            {
                retUser = -1;
            }
            else
            {
                retUser = 1;
            }
            //验证组织机构代码
            bool verifyOrgCode = false;
            if (!String.IsNullOrEmpty(dogId))
            {
                verifyOrgCode = enterpriseService.IsOrgnizationCodeExists(orgCode, corpType, "");
            }
            else
            {
                EnterpriseService.EnterpriseServiceClient enterpriseServiceClient = new EnterpriseService.EnterpriseServiceClient();
                QueryCompanyInfoCondition condition = new QueryCompanyInfoCondition();
                condition.OrginazationCode = new ParameterValue<string>() { V = orgCode, O = OptEnum.Equal };
                List<QueryCompanyInfoCondition> list = new List<QueryCompanyInfoCondition>();
                list.Add(condition);
                var result = enterpriseServiceClient.GetCompaniesInfo(JsonConvert.SerializeObject(list), "");
                var corpInfo = JsonConvert.DeserializeObject<List<Tb_Corp_CompanyInfo>>(result);
                ////2014-4-18 烟台引入招标代理企业（roleid=10506,classid=801006），与原来的代理角色不同，因此允许新旧代理企业同时存在，但不允许相同角色的存在两家
                ////判断该类型企业是否已经存在
                if (corpType == "10506")
                {
                    BasicServiceClient basicServiceClient = new BasicServiceClient();
                    var roleClassIds = JsonConvert.DeserializeObject<Dictionary<string, string>>(basicServiceClient.GetDictionary("RoleClassId", "", ""));
                    var curRoleClass = roleClassIds.Keys.Contains(corpType) ? roleClassIds[corpType] : "";
                    int classId = -1;
                    if (int.TryParse(corpType, out classId) && corpInfo.Where(c => c.classID == classId).Count() > 0)
                    {
                        verifyOrgCode = true;
                    }
                }
                else if (corpInfo != null && corpInfo.Count > 0)
                {
                    verifyOrgCode = true;
                }
            }
            if (verifyOrgCode == true)
            {
                retOrg = -2;
            }
            else
            {
                retOrg = 2;
            }

            //string output = "{{\"status1\":\"" + retUser.ToString() + "\",\"status2\":\"" + retOrg.ToString() + "\"}}";
            string output = JsonConvert.SerializeObject(new { status1 = retUser, status2 = retOrg });
            return output;
        }


        #endregion
    }
}